<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <!-- <el-form-item label="项目" >
        <el-select v-model="queryParams.projectId" filterable clearable placeholder="请选择" >
          <el-option v-for="item in projectList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备编号" prop="deviceId">
        <el-input v-model="queryParams.deviceId" placeholder="设备编号" clearable />
      </el-form-item>
      <el-form-item label="资产编号" prop="assetCode">
        <el-input v-model="queryParams.assetCode" placeholder="资产编号" clearable />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="queryParams.deviceName" placeholder="设备名称" clearable />
      </el-form-item>
      <el-form-item label="识别数量" prop="skuCount">
        <el-input v-model="queryParams.skuCount" placeholder="识别数量" clearable type="number" />
      </el-form-item>
      <el-form-item label="识别进度" prop="skuCount">
        <el-select v-model="queryParams.status" filterable clearable placeholder="请选择">
          <el-option v-for="item in this.statusList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="采集时间" prop="time">
        <el-date-picker v-model="queryParams.time" value-format="yyyy-MM-dd" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">检索</el-button>
      </el-form-item>
      <el-row>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="batchDownloadPic">批量下载图片</el-button>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="internalDownloadPic"
            v-show="$store.state.user.name === 'admin'">内部图片下载</el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <el-table v-loading="loading" :data="list" style="width: 100%" :border="true"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="在线状态" align="center" prop="status">
        <template slot-scope="scope">
          <div v-if="scope.row.status == 1">在线</div>
          <div v-if="scope.row.status == 2">待机</div>
          <div v-if="scope.row.status == 3">离线</div>
        </template>
      </el-table-column>
      <el-table-column label="位置状态" align="center" prop="position">
        <template slot-scope="scope">
          <div v-if="scope.row.position == 1">正常</div>
          <div v-if="scope.row.position == 2">偏移</div>
        </template>
      </el-table-column>
      <el-table-column label="冰柜温度" align="center" prop="temperature" />
      <el-table-column label="采集图片" align="center" prop="url">
        <template slot-scope="scope">
          <img :src="scope.row.url" class="caiImage" style="width: 100px" alt="" @click="clickPic(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="采集时间" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ scope.row.time | formatDate }}
        </template>
      </el-table-column>

      <el-table-column label="品牌型号" prop="deviceName" align="center">
        <template slot-scope="scope">
          <el-popover placement="top" width="320" trigger="hover">
            <p>设备编号 ：{{ scope.row.deviceId }}</p>
            <span slot="reference">{{ scope.row.deviceName }}</span>
            <p>资产编号 ：{{ scope.row.assetsId }}</p>
            <span slot="reference">{{ scope.row.assetsId }}</span>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="资产状态" align="center" prop="asseetsStatus" :show-overflow-tooltip="true">
        <template slot-scope="scope">
         <div v-if="scope.row.asseetsStatus==0">待分配</div>
         <div v-if="scope.row.asseetsStatus==1">待投放</div>
         <div v-if="scope.row.asseetsStatus==2">已投放</div>
        </template>
      </el-table-column>
      <el-table-column label="运营单位" align="center" prop="depId" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="运营人员" align="center" prop="sieveException" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-popover placement="top" width="320" trigger="hover">
            <p>姓名 ：{{ scope.row.name }}</p>
            <span slot="reference">{{ scope.row.name }}</span>
            <p>岗位 ：{{ scope.row.post }}</p>
            <span slot="reference">{{ scope.row.post }}</span>
            <p>电话 ：{{ scope.row.phone }}</p>
            <span slot="reference">{{ scope.row.phone }}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="门店名称" align="shopName" prop="sieveScore" :show-overflow-tooltip="true">
      </el-table-column>
      <!-- todos new add -->
      <el-table-column label="所属渠道" align="channel" prop="layer" :show-overflow-tooltip="true" />
      <el-table-column label="门店位置" align="shopLocation" :show-overflow-tooltip="true" />
      <el-table-column label="店主姓名" align="personName" :show-overflow-tooltip="true" />
      <el-table-column label="店主电话" align="personPhone" :show-overflow-tooltip="true" />
      <!-- todos new add -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
      @pagination="listResultPagination" />
    <!-- destroy-on-close 修复打开第二个modal 点击图片返回上一张 -->
    <el-dialog title="详情" :visible.sync="logDialog" :close-on-click-modal="false" width="70%" destroy-on-close
      destroy-on-closescope>
      <el-button style="margin-bottom: 10px" size="small" @click="handleDownload" icon="el-icon-download">下载图片</el-button>
      <div class="analy-container">
        <!-- <div ref="canvasBox" style="width: 100%"> -->
        <div ref="canvasBox" class="composeImage">
          <canvas ref="canvas"></canvas>
        </div>

        <div style="margin-left: 100px">
          <!-- todos展示的表格 需要自己数据计算 -->
          <el-table :data="standardValue" style="width: 100%">
            <el-table-column label="指标值" prop="name" align="center">
            </el-table-column>
            <el-table-column label="标准值" prop="standardValue" align="center">
              <template slot-scope="scope">
                {{ scope.row.standardValue }}%
              </template>
            </el-table-column>
            <el-table-column label="实际值" prop="realValue" align="center">
              <template slot-scope="scope">
                {{ scope.row.realValue }}%
              </template>


            </el-table-column>
            <el-table-column label="结果" prop="result" align="center">
              <template slot-scope="scope">
                <div :style="{ color: scope.row.result === '不满足' || scope.row.result === '缺货' ? 'red' : 'green' }">
                  {{ scope.row.result }}
                </div>

              </template>
            </el-table-column>


          </el-table>

          <el-table :data="threeType" style="width: 100%">
            <el-table-column label="项目" prop="name" align="center">
            </el-table-column>
            <el-table-column label="所在层数" prop="layer" align="center">
            </el-table-column>
            <el-table-column label="排面数/个" prop="paimian" align="center">
            </el-table-column>
            <el-table-column label="排面占比" prop="paimainRate" align="center">
              <template slot-scope="scope">
                {{ scope.row.paimainRate }}%
              </template>
            </el-table-column>
            <el-table-column label="品项/个" prop="pinxiang" align="center">
            </el-table-column>
            <el-table-column label="品项占比" prop="pingxiangRate" align="center">
              <template slot-scope="scope">
                {{ scope.row.pingxiangRate }}%
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 陈列明细 -->
      <el-table :data="currentLog && currentLog.skuList" style="width: 100%">
        <el-table-column label="sku名称" prop="name" align="center">
        </el-table-column>
        <el-table-column label="所在层数" prop="skuLayer" align="center">
        </el-table-column>
        <el-table-column label="排面数量" prop="skuNum" align="center">
        </el-table-column>
        <el-table-column label="排面占比" prop="skuRate" align="center">
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="logDialog = false">取 消</el-button>
        <el-button type="primary" @click="logDialog = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="图片下载" :visible.sync="dialogOpen" :close-on-click-modal="false" width="800px" append-to-body>
      <el-form label-width="120px" :rules="queryInternalFormRules" ref="queryInternalForm" :model="queryInternal">
        <el-row>
          <el-col :span="12">
            <el-form-item label="选择查询方式">
              <el-select v-model="queryInternal.select" clearable placeholder="请选择" :disabled="showOneLevel"
                @change="changeSearchWay">
                <el-option v-for="item in selection" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名称" v-if="queryInternal.select == 0">
              <el-select v-model="queryInternal.userId" clearable placeholder="请选择" :disabled="showOneLevel"
                @change="selectChange(1)">
                <el-option v-for="item in initCustomer" :key="item.id" :label="item.nickname" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备Id" v-if="queryInternal.select == 1">
              <el-input v-model="queryInternal.deviceId" placeholder="请输入设备ID"></el-input>
            </el-form-item>
          </el-col>

          <el-col>
            <el-form-item label="日期" prop="time">
              <el-date-picker v-model="queryInternal.time" value-format="yyyy-MM-dd" type="date" placeholder="请选择">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="第几张图片" prop="index">
              <el-input v-model.number="queryInternal.index" type="number" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitContainer">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import loadZip from '@/utils/loadZip.js'
// import ExportExcel from '@/components/ExcelUtils/ExportExcel'
// import { userListSon } from '@/api/user'
// import { getRecordInfo, deleteResult, getUserIdByDeviceId, getListImage } from '@/api/record.js'
// import html2canvas from 'html2canvas'
import { fabric } from 'fabric'
import moment from 'moment'
// import { getSKULibList, getUserSKUList } from '@/api/goods/SKU'
// import { bipupinList } from '@/api/dataCenter'
// import { getToken } from '@/utils/auth'
// import { displaySpecGet, listCustomer } from '@/api/customer/customer'
// import initCust from '@/plugins/mixin'
// todos 排面标准值页面另外需要一个页面
const standardValue = [
  { name: '纯净度', standardValue: '-', realValue: '-', result: '-' },
  { name: '饱和度', standardValue: '-', realValue: '-', result: '-' },
  { name: '黄金位纯度', standardValue: '-', realValue: '-', result: '-' },
  { name: '缺货率', standardValue: '-', realValue: '-', result: '-' },
  { name: '必辅品率', standardValue: '-', realValue: '-', result: '-' },
]
// 本品 竞品 和 他品
const threeType = [
  {
    name: '本品',
    layer: '-',
    paimian: '-',
    paimainRate: '-',
    pinxiang: '-',
    pingxiangRate: '-',
  },
  {
    name: '竞品',
    layer: '-',
    paimian: '-',
    paimainRate: '-',
    pinxiang: '-',
    pingxiangRate: '-',
  },
  {
    name: '他品',
    layer: '-',
    paimian: '-',
    paimainRate: '-',
    pinxiang: '-',
    pingxiangRate: '-',
  },
]

export default {
  name: 'Online',
  // mixins: [initCust],
  data() {
    return {
      downloadUrl: '',
      //选中行的列表
      ids: [],
      // 选中行的图片url数组
      urls: [],
      deviceId: '',//当前选择查看的图片的设备id
      skuPosition: 0,
      showOneLevel: false,
      showTwoLevel: true,
      showThreeLevel: true,
      showFourLevel: true,
      showFiveLevel: true,
      dialogOpen: false, // 内部图片下载弹窗
      tValue: ['url'],
      tHeader: ['图片url'],
      listImage:[],
      listUrl:[],
      queryInternal: {
        select: 0,
        userId: '',
        deviceId: '',
        time: '',
        index: 1,
      },
      selection: [
        {
          label: '按用户搜索',
          value: 0
        },
        {
          label: '按设备搜索',
          value: 1
        }
      ],
      //表单校验
      queryInternalFormRules: {
        time: [{ required: true, message: '请选择', trigger: 'blur' }],
        index: [{ message: '最小值为1', trigger: 'blur', type: 'number', min: 1 }],
      },
      // 检索*级用户
      twoLevelUserListSearch: [],
      threeLevelUserListSearch: [],
      fourLevelUserListSearch: [],
      fiveLevelUserListSearch: [],
      tableList: [
        {
          bipupinCount: '',
          userName: '',
          containerModelName: '',
          goldenPosLayer: '',
          goldenPosPurity: '',
          purity: '',
          saturation: '',
          stockOutRate: '',
          // algorithm:''
        },
      ],
      skuTableInfo: [],
      // initCustomer: [],
      threeType,
      standardValue,
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      pageNum: 1,
      pageSize: 20,
      // 查询参数
      queryParams: {
        userId: '',    //一级用户，商户
        twoUserId: '',     //二级用户，一级经销商，品牌方
        threeUserId: '',   //三级用户，二级经销商
        fourUserId: '',    //四级用户，三级经销商
        fiveUserId: '',    //五级用户，四级经销商
        deviceId: '',   //设备id
        deviceName: '',   //设备名称
        skuCount: '',   //识别数量
        assetCode: '',   //资产编号
        status: '',  //识别进度
        time: ''   //采集时间
      },
      currentLog: null, // 当前查看的识别记录
      logDialog: false,
      statusList: [
        {
          label: '识别中',
          value: 0
        },
        {
          label: '识别成功',
          value: 1
        },
        {
          label: '识别失败',
          value: 2
        }
      ],
    }
  },
  created() {
    //根据level去判断和赋值
    if (this.$store.state.user.level === 1) {
      if (this.$store.state.user.name === 'admin') {
        this.showOneLevel = false
        //console.log('showOneLevel',this.showOneLevel);

      } else {
        this.showOneLevel = true
      }
      this.queryParams.userId = this.$store.state.user.id
      this.selectChange(1)
    } else if (this.$store.state.user.level === 2) {
      this.queryParams.twoUserId = this.$store.state.user.id
      this.showOneLevel = true
      this.showTwoLevel = true
      var loginUser = [
        {
          id: this.$store.state.user.id,
          nickname: this.$store.state.user.nickname
        }
      ]
      this.twoLevelUserListSearch = loginUser
      //获取子用户
      this.selectChange(2)
    } else if (this.$store.state.user.level === 3) {
      this.queryParams.threeUserId = this.$store.state.user.id
      this.showOneLevel = true
      this.showTwoLevel = true
      this.showThreeLevel = true
      var loginUser = [
        {
          id: this.$store.state.user.id,
          nickname: this.$store.state.user.nickname
        }
      ]
      this.threeLevelUserListSearch = loginUser
      this.selectChange(3)
    } else if (this.$store.state.user.level === 4) {
      this.queryParams.fourUserId = this.$store.state.user.id
      this.showOneLevel = true
      this.showTwoLevel = true
      this.showThreeLevel = true
      this.showFourLevel = true
      var loginUser = [
        {
          id: this.$store.state.user.id,
          nickname: this.$store.state.user.nickname
        }
      ]
      this.fourLevelUserListSearch = loginUser
      this.selectChange(4)
    } else {
      this.queryParams.fiveUserId = this.$store.state.user.id
      this.showOneLevel = true
      this.showTwoLevel = true
      this.showThreeLevel = true
      this.showFourLevel = true
      this.showFiveLevel = true
      var loginUser = [
        {
          id: this.$store.state.user.id,
          nickname: this.$store.state.user.nickname
        }
      ]
      this.fiveLevelUserListSearch = loginUser
      this.selectChange(5)
    }
    this.loading = true
    this.getList()
  },
  mounted() {

  },
  filters: {
    status2Text(value) {
      const mapText = {
        0: '识别中',
        1: '识别成功',
        2: '识别失败',
      }
      return mapText[value]
    },
  },
  methods: {
    //内部图片下载弹窗
    internalDownloadPic() {
      this.dialogOpen = true;

      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let day = now.getDate();
      if (day < 10) {
        day = '0' + day
      }
      if (month < 10) {
        month = '0' + month
      }
      this.queryInternal.time = year + '-' + month + '-' + day
      this.queryInternal.userId = ''
      this.queryInternal.deviceId = ''
      this.queryInternal.index = 1
      //获取用户 设备  
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j == 'isUsed') {
          return v.isUsed === 0 ? '未使用' : '已使用'
        } else {
          return v[j]
        }
      }))
    },
    //内部图片下载确定
    submitContainer() {

      this.$refs.queryInternalForm.validate((valid) => {
        if (!valid) {
          console.log('error submit!!', this.queryInternal);

          return
        }
        const params = {
          index: this.queryInternal.index,
          userId: this.queryInternal.userId,
          deviceId: this.queryInternal.deviceId,
          date: this.queryInternal.time
        }
        if (this.queryInternal.userId == '' && this.queryInternal.deviceId == '') {
          this.$message.error('请选择用户名称或设备Id')
          return
        }
        this.listImage = []
        // getListImage(params)
        //   .then((res) => {
        //     res.data.forEach(item=>{
        //       this.listImage.push({'url':item})
        //     })   
        //   })
        //   .finally(() => {
        //     //导出excel
        //     import('@/components/ExcelUtils/ExportExcel.js').then(excel => {
        //       const data = this.formatJson(this.tValue, this.listImage)
        //       console.log('data',data);
        //       excel.export_json_to_excel({
        //         header: this.tHeader,
        //         data: data,
        //         filename: `内部图片压缩包_${new Date().getTime()}`,
        //         autoWidth: true,
        //         bookType: 'xlsx'
        //       })
        //     })


        //     //导出zip
        //     // if (this.listImage.length !== 0) {
        //     //   let fileArr = []
        //     //   for (var i = 0; i < this.listImage.length; i++) {
        //     //     let fileTemp = {
        //     //       fvUrl: this.listImage[i],
        //     //       fvName: i + '.jpg'
        //     //     }
        //     //     fileArr.push(fileTemp)
        //     //   }
        //     //   var zipName = `内部图片压缩包_${new Date().getTime()}`
        //     //   //使用一个轮子
        //     //   loadZip(fileArr, zipName)
        //     // } else {
        //     //   this.$message.info("当前没有图片")
        //     // }
        //     this.dialogOpen = false;
        //   })
      })

    },
    /** 点击选中 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.urls = selection.map(item => item.url)
    },
    /** 点击批量下载按钮 */
    batchDownloadPic() {
      if (this.urls) {
        let fileArr = []
        for (var i = 0; i < this.urls.length; i++) {
          let fileTemp = {
            fvUrl: this.urls[i],
            fvName: i + '.jpg'
          }
          fileArr.push(fileTemp)
        }
        var zipName = `算法图片压缩包_${new Date().getTime()}`
        //使用一个轮子
        // loadZip(fileArr, zipName)
      } else {
        this.$message.info("请先选择要下载的数据！")
      }
    },
    clickPic(row) {
      this.downloadUrl = row.url
      this.skuPosition = 0
      this.deviceId = row.deviceId
      this.getDevicesSkuInfoLoad(row)
    },
    getDevicesSkuInfoLoad(row) {
      this.deviceRecResult = row
      this.algorithmVersion = this.deviceRecResult.algorithm
      this.containerTypeId = this.deviceRecResult.containerTypeId
      this.userId = this.deviceRecResult.userId
      this.displayVolume = this.deviceRecResult.displayVolume
      this.picTime = this.deviceRecResult.time
      this.getDisplaySpec()
    },
    getDisplaySpec() {
      const params = {
        userId: this.userId,
        containerTypeId: this.containerTypeId
      }
      // displaySpecGet(params).then((res) => {
      //   console.log("第二步", res)
      //   if (res.data.length > 0) {
      //     this.goldenPosLayer = res.data[0].goldenPosLayer
      //     this.standardValue[0].standardValue = res.data[0].purity
      //     this.standardValue[1].standardValue = res.data[0].saturation
      //     this.standardValue[2].standardValue = res.data[0].goldenPosPurity
      //     this.standardValue[3].standardValue = res.data[0].stockOutRate
      //     this.standardValue[4].standardValue = res.data[0].biPuPinRate
      //     this.displayVolume = this.deviceRecResult.displayVolume
      //   }
      // }).finally(() => {
      //   this.getSKUTableInfo()
      // })
    },
    getSKUTableInfo() {
      //接口是分页的，目前获取就先写死10000条
      // getUserSKUList({
      //   pageIndex: 0,
      //   pageSize: 10000,
      //   userId: this.userId
      // })
      //   .then((res) => {
      //     if (res && res.data) {
      //       this.skuTableInfo = res.data.data
      //     }
      //   }).catch(() => {
      //     console.log("getUserSKUList调用失败" || err.message)
      //   }).finally(() => {
      //     const listData = this.analyserData(this.deviceRecResult)
      //     if (typeof (listData) !== 'undefined') {
      //       this.skuList = listData?.skuList
      //       this.showLog(listData)
      //       let BenPinCount = 0
      //       let BiPuPinCount = 0
      //       let JingPinCount = 0
      //       let TaPinCount = 0
      //       for (var i = 0; i < listData.skuList.length; i++) {
      //         let item = listData.skuList[i]
      //         if (item.classify === 0) {
      //           if (item.biPuPin === true) {
      //             BiPuPinCount = BiPuPinCount + item.skuNum
      //             BenPinCount = BenPinCount + item.skuNum
      //           } else {
      //             BenPinCount = BenPinCount + item.skuNum
      //           }
      //         } else if (item.classify === 1) {
      //           JingPinCount = JingPinCount + item.skuNum
      //         } else if (item.classify === 2) {
      //           TaPinCount = TaPinCount + item.skuNum
      //         }
      //       }


          //   //纯净度实际值
          //   if (BenPinCount === 0 || listData.totalCount === 0) {
          //     this.standardValue[0].realValue = 0
          //   } else {
          //     this.standardValue[0].realValue = ((BenPinCount / listData.totalCount) * 100).toFixed(2)
          //   }
          //   //饱和度实际值
          //   if (listData.totalCount === 0) {
          //     this.standardValue[1].realValue = 0
          //   } else {
          //     this.standardValue[1].realValue = (((listData.totalCount / this.displayVolume) * 100).toFixed(2))
          //     if(this.standardValue[1].realValue > 100){
          //       this.standardValue[1].realValue = 100
          //     }
          //   }

          //   //黄金位纯度实际值
          //   if (listData.goldPurityRate === 0) {
          //     this.standardValue[2].realValue = 0
          //   } else {
          //     this.standardValue[2].realValue = listData.goldPurityRate
          //   }


          //   //缺货率实际值
          //   if (listData.totalCount === 0) {
          //     this.standardValue[3].realValue = 0
          //   } else {
          //     this.standardValue[3].realValue = (100 - this.standardValue[1].realValue).toFixed(2)
          //   }


          //   //必铺品率实际值
          //   if (BiPuPinCount === 0 || listData.totalCount === 0) {
          //     this.standardValue[4].realValue = 0
          //   } else {
          //     this.standardValue[4].realValue = (((BiPuPinCount / listData.totalCount) * 100).toFixed(2))
          //   }

          //   //识别结果
          //   for (var i = 0; i < 5; i++) {
          //     //两个值都存在才能进行比较
          //     if (this.standardValue[i].standardValue !== '-' && this.standardValue[i].realValue !== '-') {
          //       //要先把String转成number类型再进行比较，转成number两种方法一种*1 一种-0 
          //       let real = this.standardValue[i].realValue * 1
          //       let stand = this.standardValue[i].standardValue * 1
          //       //i===3为缺货率 实际值大于标准值的话 ，显示缺货
          //       if (i === 3) {
          //         if (stand < real) {
          //           this.standardValue[i].result = '缺货'
          //         } else {
          //           this.standardValue[i].result = '不缺货'
          //         }
          //       } else {
          //         if (stand <= real) {
          //           this.standardValue[i].result = '满足'
          //         } else {
          //           this.standardValue[i].result = '不满足'
          //         }
          //       }

          //     }
          //   }

          //   //所在层数匹配
          //   this.threeType[0].layer = listData.BenPinLayer
          //   this.threeType[1].layer = listData.JingPinLayer
          //   this.threeType[2].layer = listData.TaPinLayer

          //   //排面数/个匹配
          //   this.threeType[0].paimian = BenPinCount
          //   this.threeType[1].paimian = JingPinCount
          //   this.threeType[2].paimian = TaPinCount

          //   //牌面总数

          //   let paimianTotal = this.threeType[0].paimian + this.threeType[1].paimian + this.threeType[2].paimian
          //   //排面占比匹配
          //   if (paimianTotal === 0) {
          //     this.threeType[0].paimainRate = 0
          //     this.threeType[1].paimainRate = 0
          //     this.threeType[2].paimainRate = 0
          //   } else {
          //     if (BenPinCount === 0) {
          //       this.threeType[0].paimainRate = 0
          //     } else {
          //       this.threeType[0].paimainRate = (((this.threeType[0].paimian / paimianTotal) * 100).toFixed(2))
          //     }

          //     if (JingPinCount === 0) {
          //       this.threeType[1].paimainRate = 0
          //     } else {
          //       this.threeType[1].paimainRate = (((this.threeType[1].paimian / paimianTotal) * 100).toFixed(2))
          //     }

          //     if (TaPinCount === 0) {
          //       this.threeType[2].paimainRate = 0
          //     } else {
          //       this.threeType[2].paimainRate = (((this.threeType[2].paimian / paimianTotal) * 100).toFixed(2))
          //     }
          //   }

          //   //品项/个匹配
          //   this.threeType[0].pinxiang = listData.BenPinPinXiang
          //   this.threeType[1].pinxiang = listData.JingPinPinXiang
          //   this.threeType[2].pinxiang = listData.TaPinPinXiang

          //   //品项总数
          //   let pinxiangTotal = listData.BenPinPinXiang + listData.JingPinPinXiang + listData.TaPinPinXiang

          //   //品项占比匹配
          //   if (pinxiangTotal === 0) {
          //     this.threeType[0].pingxiangRate = 0
          //     this.threeType[1].pingxiangRate = 0
          //     this.threeType[2].pingxiangRate = 0
          //   } else {
          //     if (listData.BenPinPinXiang === 0) {
          //       this.threeType[0].pingxiangRate = 0
          //     } else {
          //       this.threeType[0].pingxiangRate = (((this.threeType[0].pinxiang / pinxiangTotal) * 100).toFixed(2))
          //     }
          //     if (listData.JingPinPinXiang === 0) {
          //       this.threeType[1].pingxiangRate = 0
          //     } else {
          //       this.threeType[1].pingxiangRate = (((this.threeType[1].pinxiang / pinxiangTotal) * 100).toFixed(2))
          //     }
          //     if (listData.TaPinPinXiang === 0) {
          //       this.threeType[2].pingxiangRate = 0
          //     } else {
          //       this.threeType[2].pingxiangRate = (((this.threeType[2].pinxiang / pinxiangTotal) * 100).toFixed(2))
          //     }
          //   }


          // }
        //})
    },
    //内部图片下载改变查询方式
    changeSearchWay() {
      this.queryInternal.userId = ''
      this.queryInternal.deviceId = ''
    },
    //搜索框用户选择改变
    selectChange(level) {
      if (level === 1) {
        this.queryParams.twoUserId = ''
        this.queryParams.threeUserId = ''
        this.queryParams.fourUserId = ''
        this.queryParams.fiveUserId = ''
        this.showTwoLevel = true
        this.showThreeLevel = true
        this.showFourLevel = true
        this.showFiveLevel = true
        this.paramId = this.queryParams.userId
      } else if (level === 2) {
        this.queryParams.threeUserId = ''
        this.queryParams.fourUserId = ''
        this.queryParams.fiveUserId = ''
        this.showThreeLevel = true
        this.showFourLevel = true
        this.showFiveLevel = true
        this.paramId = this.queryParams.twoUserId
      } else if (level === 3) {
        this.queryParams.fourUserId = ''
        this.queryParams.fiveUserId = ''
        this.showFourLevel = true
        this.showFiveLevel = true
        this.paramId = this.queryParams.threeUserId
      } else if (level === 4) {
        this.queryParams.fiveUserId = ''
        this.showFiveLevel = true
        this.paramId = this.queryParams.fourUserId
      } else {
        this.paramId = this.queryParams.fiveUserId
      }
      // userListSon({ userId: this.paramId }).then((res) => {
      //   if (res.data != '') {
      //     if (level === 1) {
      //       this.twoLevelUserListSearch = res.data
      //       this.showTwoLevel = false
      //     } else if (level === 2) {
      //       this.threeLevelUserListSearch = res.data
      //       this.showThreeLevel = false
      //     } else if (level === 3) {
      //       this.fourLevelUserListSearch = res.data
      //       this.showFourLevel = false
      //     } else if (level === 4) {
      //       this.fiveLevelUserListSearch = res.data
      //       this.showFiveLevel = false
      //     }

      //   }
      // }).catch((err) => {
      //   console.log('## err ==> ', err)
      // })
      //最后强制刷新
      this.$forceUpdate();
    },
    handleDownload() {
      // 支持下载图片
      // html2canvas(this.$refs.canvasBox, {
      //   // allowTaint: false
      //   useCORS: true,
      // }).then(canvas => {
      //   // html2canvas(document.querySelector('.lower-canvas')).then(canvas => {
      //   let url = canvas.toDataURL('image/png')
      //   this.download(url)
      // })
    },
    download(url) {
      let doma = document.createElement('a')
      doma.download = ''
      // doma.href = url
      doma.href = this.currentLog.url
      document.body.appendChild(doma)
      doma.click()
      doma.remove()
    },
    listResultPagination() {
      this.getList()
    },
    // 删除前二次确认
    handleDelete(row) {
      this.$confirm('是否删除？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      })
        .then(() => {
          this.deleteRow(row)
        })
        .catch(() => { })
    },
    // 删除单条数据
    deleteRow(row) {
      this.loading = true
      // deleteResult({ id: row.id })
      //   .then((res) => {
      //     // 刷新列表数据
      //     this.getList()
      //   })
      //   .catch((err) => {
      //     this.$message.error(err.message || '删除失败')
      //   })
      //   .finally(() => {
      //     this.loading = false
      //   })
    },
    /** 查询 */
    getList(obj = {}) {
      const { time } = this.queryParams
      let startTime = ''
      let endTime = ''
      if (Array.isArray(time) && time.length > 0) {
        const [s, e] = time
        startTime = moment(s).format('yyyy-MM-DD')
        endTime = moment(e).format('yyyy-MM-DD')
      }
      this.loading = true

      let bingdingUserId
      //绑定要查找的用户id
      if (this.queryParams.fiveUserId != '') {
        bingdingUserId = this.queryParams.fiveUserId
      } else if (this.queryParams.fourUserId != '') {
        bingdingUserId = this.queryParams.fourUserId
      } else if (this.queryParams.threeUserId != '') {
        bingdingUserId = this.queryParams.threeUserId
      } else if (this.queryParams.twoUserId != '') {
        bingdingUserId = this.queryParams.twoUserId
      } else {
        bingdingUserId = this.queryParams.userId
      }
      const params = {
        pageIndex: this.pageNum - 1,
        pageSize: this.pageSize,
        deviceId: this.queryParams.deviceId,
        deviceName: this.queryParams.deviceName,
        userId: bingdingUserId,
        assetCode: this.queryParams.assetCode,
        skuCount: this.queryParams.skuCount ? parseInt(this.queryParams.skuCount) : '',
        status: this.queryParams.status,
        startTime,
        endTime,
        ...obj,
      }
      // getRecordInfo(params)
      //   .then((res) => {
      //     if (res && res.data) {
      //       // const listData = this.analyserData(res.data?.data)
      //       // this.list = res.data.data
      //       this.list = res.data.data
      //       this.pageNum = res.data.pageIndex + 1
      //       this.total = res.data.totalCount
      //     }
      //   })
      //   .finally(() => {
      //     this.loading = false
      //   })

    },
    //算法分析
    analyserData(data = []) {
      let BenPinLayer = []
      let JingPinLayer = []
      let TaPinLayer = []
      let BenPinPinXiangList = []
      let JingPinPinXiangList = []
      let TaPinPinXiangList = []
      let BenPinPinXiang = 0
      let JingPinPinXiang = 0
      let TaPinPinXiang = 0
      let goldPurityRate
      let parseObj = null
      let layerList = []
      let skuNumMap = new Map()
      let layer = ''
      let totalCount
      // 陈列列表
      let skuList = []
      try {
        parseObj = JSON.parse(data.data)
        if (parseObj) {
          if (parseObj.results) {
            //统计sku的名称、统计各个sku的数量（去重）
            parseObj.results.forEach((item) => {
              if (!skuNumMap.has(item.customerSkuCode)) {
                skuNumMap.set(item.customerSkuCode, 1)
              } else {
                skuNumMap.set(item.customerSkuCode, skuNumMap.get(item.customerSkuCode) + 1)
              }
            })
            for (var i = 0; i < skuNumMap.size; i++) {
              let temp = {
                name: '',
                skuNum: 0,
                skuRate: '',
                biPuPin: '',
                classify: '',
                skuLayer: [],
                skuCode: ''
              }
              skuList.push(temp)
            }
            //sku数量和名称和占比
            totalCount = parseObj.statistics.known_sku_facing;
            skuNumMap.forEach((value, key, self) => {
              skuList[this.skuPosition].skuCode = key
              skuList[this.skuPosition].skuNum = value
              skuList[this.skuPosition].skuRate = ((value / totalCount) * 100).toFixed(2) + '%'
              this.skuPosition++
            })
            //品类和必铺品
            for (var i = 0; i < skuList.length; i++) {
              this.skuTableInfo.forEach((skuItem) => {
                //todos 根据算法返回的customerSkuCode去和商品列表的
                if (skuItem.skuId == skuList[i].skuCode) {
                  //把算法识别返回的数据中加入 是否为必铺品、品类、层数（在第几层）
                  skuList[i].biPuPin = skuItem.biPuPin
                  skuList[i].classify = skuItem.classify
                }
              })
            }
            //所在层数
            parseObj.results.forEach((res) => {
              for (var i = 0; i < skuList.length; i++) {
                if (skuList[i].skuCode == res.customerSkuCode && !skuList[i].skuLayer.includes(res.layer)) {
                  if (skuList[i].skuLayer.length !== 0) {
                    skuList[i].skuLayer.push(',')
                    skuList[i].skuLayer.push(res.layer)
                  } else {
                    skuList[i].skuLayer.push(res.layer)
                  }
                  skuList[i].name = res.customerSkuName
                }
              }
            })


          }
          let goldLayerSum = 0
          let goldLayerBenPinSum = 0
          let goldLayerNum = []
          if (parseObj.results) {
            //判断接口返回的黄金层数是否包含逗号
            if (this.goldenPosLayer != '') {
              if (this.goldenPosLayer.indexOf(',')) {
                goldLayerNum.push(this.goldenPosLayer.split(','))
              } else {
                goldLayerNum.push(this.goldenPosLayer)
              }
            }

            parseObj.results.forEach((item) => {
              for (var i = 0; i < goldLayerNum[0].length; i++) {
                if (goldLayerNum[0][i] == item.layer) {

                  if (item.classify == 0) {

                    goldLayerBenPinSum = goldLayerBenPinSum + 1
                    goldLayerSum = goldLayerSum + 1
                  } else {
                    goldLayerSum = goldLayerSum + 1
                  }
                }
              }
            })
          }

          //黄金位纯度实际值
          if (goldLayerBenPinSum === 0 || goldLayerSum === 0) {
            goldPurityRate = 0
          } else {
            goldPurityRate = ((goldLayerBenPinSum / goldLayerSum) * 100).toFixed(2)
          }

          //本品、竞品、他品 层数统计
          parseObj.results.forEach((item) => {
            //todos 统计 本竟他的数量 
            if (item.classify === 0 && !BenPinLayer.includes(item.layer)) {
              BenPinLayer.push(item.layer)
            } else if (item.classify === 1 && !JingPinLayer.includes(item.layer)) {
              JingPinLayer.push(item.layer)
            } else if (item.classify === 2 && !TaPinLayer.includes(item.layer)) {
              TaPinLayer.push(item.layer)
            }
          })
          //
          // parseObj.results.forEach((item) => {
          //   //todos 统计 本竟他的数量 
          //   if(item.classify === 0 ){
          //     if(item.biPuPin){
          //       BiPuPinCount ++
          //     }
          //     BenPinCount ++
          //   }else if(item.classify === 1 ){
          // 	  JingPinCount ++
          //   }else if(item.classify === 2 ){
          // 	  TaPinCount ++
          //   }
          // })
          //给返回的层数加上逗号
          BenPinLayer = BenPinLayer.join(',')
          JingPinLayer = JingPinLayer.join(',')
          TaPinLayer = TaPinLayer.join(',')


          //品项统计
          parseObj.results.forEach((item) => {
            if (item.classify === 0 && !BenPinPinXiangList.includes(item.name)) {
              BenPinPinXiangList.push(item.name)
            } else if (item.classify === 1 && !JingPinPinXiangList.includes(item.name)) {
              JingPinPinXiangList.push(item.name)
            } else if (item.classify === 2 && !TaPinPinXiangList.includes(item.name)) {
              TaPinPinXiangList.push(item.name)
            }
          })

          BenPinPinXiang = BenPinPinXiangList.length
          JingPinPinXiang = JingPinPinXiangList.length
          TaPinPinXiang = TaPinPinXiangList.length
          layer = layerList.length






        }
      } catch (error) {
        console.log('## 数据解析失败', error)
      }
      return {
        ...data,
        layer,
        totalCount,
        // 陈列列表
        skuList,
        //黄金层纯度
        goldPurityRate,
        //三种品类的货架子号
        BenPinLayer,
        JingPinLayer,
        TaPinLayer,
        //三种品类的品项数
        BenPinPinXiang,
        JingPinPinXiang,
        TaPinPinXiang
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      // if (this.total > this.pageNum * this.pageSize) {
      //   this.pageNum += 1
      //   this.getList()
      // }
      this.getList({
        pageIndex: 0,
      })
    },
    getBase64(imgUrl) {
      return new Promise((resolve) => {
        // window.URL = window.URL || window.webkitURL
        var xhr = new XMLHttpRequest()
        xhr.open('get', imgUrl, true)
        xhr.responseType = 'blob'
        xhr.onload = function () {
          if (this.status == 200) {
            //得到一个blob对象
            var blob = this.response
            // 至关重要
            let oFileReader = new FileReader()
            oFileReader.onloadend = function (e) {
              // 此处拿到的已经是base64的图片了,可以赋值做相应的处理
              resolve(e.target.result)
            }
            oFileReader.readAsDataURL(blob)
          }
        }
        xhr.send()
      })
    },


    /**
     * 查看
     * @param {Object} log  当前日志信息
     */
    showLog(log) {
      this.currentLog = log
      this.logDialog = true
      this.$nextTick(() => {

        // if (!this. canvas) {
        //指定容器高度
        const h = 500
        this.$refs.canvasBox.style.height = h + 'px'

        // }
        // canvas.clear()

        //对图片进行渲染-图像文件的加载是异步的，所有对Image的后续操作都要在回调中完成
        fabric.Image.fromURL(
          log.url + `?${new Date().getTime()}`,
          (img) => {
            let w
            img.set({ selectable: false })

            // if (img.width > img.height) {
            //   img.scaleToWidth(h)

            //   w = img.height * img.scaleX
            //   img.set({ angle: -90, top: h })
            // } else {
            //   img.scaleToHeight(h)
            //   w = img.width * img.scaleX
            // }
            img.scaleToWidth(430)  //指定宽度
            img.scaleToHeight(500)  //指定图片高度
            w = img.width * img.scaleX
            const canvas = new fabric.Canvas(this.$refs.canvas, {
              width: w,
              height: h,
              centeredRotation: true,
            })
            //加入新图片之前把老的清空了
            // canvas.clear()
            canvas.add(img)
            let results = []
            try {
              const data = JSON.parse(log.data)
              results = data.results || []
              //用商品名替换掉算法名
              if (results.length > 0) {
                results.forEach((item) => {
                  this.skuTableInfo.forEach((skuItem) => {
                    if (skuItem.libSkuName === item.name.substring(0, item.name.indexOf("_"))) {
                      item.name = skuItem.skuName
                    }
                  })
                })
              }

            } catch (error) { }
            // 1 本品 绿色框 2 竞品 红色框 3 未知 蓝色框
            const strokeColors = ['#669933', '#ff6666', '#99CCFF']
            const shadowColors = ['green', 'red', 'blue']
            for (let i = 0; i < results.length; i++) {

              const res = results[i]
              const loc = res.location

              // if (img.width > img.height) {
              //   let t = loc.top
              //   loc.top = loc.left
              //   loc.left = t
              //   t = loc.width
              //   loc.width = loc.height
              //   loc.height = t
              // }
              loc.top = loc.top * img.scaleY
              loc.height = loc.height * img.scaleY
              loc.left = loc.left * img.scaleX
              loc.width = loc.width * img.scaleX
              if (!loc) continue
              const colroI = parseInt(Math.random() * 3)
              const stroke = strokeColors[colroI]
              const shadowColor = shadowColors[colroI]
              const shadow = new fabric.Shadow({ color: shadowColor, blur: 0 })
              const rect = new fabric.Rect({
                ...loc,
                fill: 'transparent',
                strokeWidth: 2,
                stroke,
                lockMovementX: true,
                lockMovementY: true,
                hasControls: false,
                hasBorders: false,
              })
              const text = new fabric.Text(res.name, {
                ...loc,
                fontSize: 14,
                stroke: shadowColor,
              })
              text.set('left', text.left - text.width / 2 + loc.width / 2)
              text.set('top', text.top - text.height)
              const Trect = new fabric.Rect({
                top: text.top,
                left: text.left,
                width: text.width,
                height: text.height,
                fill: '#ffffff',
              })
              const tg = new fabric.Group([Trect, text], {
                lockMovementX: true,
                lockMovementY: true,
                hasControls: false,
                hasBorders: false,
              })
              // g.shadow.blur = 0
              rect.on('selected', () => {
                // rect.shadow.blur = 10
                // rect.shadow.color = shadowColor
                rect.set('stroke', shadowColor)
                rect.set('strokeWidth', 4)
                // rect.renderAll()
                canvas.add(tg)
              })
              rect.on('deselected', () => {
                // rect.shadow.blur = 0
                // rect.shadow.color = stroke
                rect.set('stroke', stroke)
                rect.set('strokeWidth', 2)
                canvas.remove(tg)
              })
              canvas.add(rect)

            }
            //监听canvas点击事件
            canvas.on('mouse:down', function (options) {
              // html2canvas(document.querySelector('.lower-canvas')).then(canvas => {
              // let url = canvas.toDataURL('image/png')
            })
            canvas.renderAll()

          },
          { crossOrigin: 'anonymous' }
        )
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.caiImage:hover {
  cursor: pointer;
}

.el-table .cell {
  white-space: pre-line !important;
}

.analy-container {
  display: flex;
}
</style>



